<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
</head>
<body>
<div style="margin: 20px auto; max-width: 1140px">
    <div class="layui-row " style="position: relative;right: 93px">
        <div class="layui-col-md10 layui-col-md-offset1">
            <div class="demoTable">
                <div class="layui-inline">
                    <input class="layui-input" name="userName" id="userName" placeholder="请输入姓名">
                </div>
                <div class="layui-inline">
                    <select class="layui-inline" name="roleId" id="queryRoleSelect" style="display: inline-block;height: 35px"></select>
                    <select class="layui-inline" name="userStatus" id="userStatusSelect" style="display: inline-block;height: 35px">
                        <option value="0" disabled selected>请选择状态</option>
                        <option value="1">启用</option>
                        <option value="2">停用</option>
                    </select>
                </div>
                <button class="layui-btn" data-type="reload">搜索</button>
                <button class="layui-btn" id="resetButton">重置</button>
            </div>
        </div>
    </div>
</div>
<table class="layui-hide" id="test" lay-filter="test"></table>

<div id="userItem" style="display: none;position: relative;margin: 50px">
    <form class="layui-form layui-form-pane" lay-filter="viewForm">
        <div class="layui-form-item">
            <label class="layui-form-label">用户姓名</label>
            <div class="layui-input-inline">
                <input type="text" name="userName" lay-verify="required" autocomplete="off" class="layui-input"
                       disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户账号</label>
            <div class="layui-input-inline">
                <input type="text" name="userUsername" lay-verify="required" autocomplete="off" class="layui-input"
                       disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">职务</label>
            <div class="layui-input-inline">
                <input type="text" name="roleName" lay-verify="required" autocomplete="off" class="layui-input"
                       disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">权限</label>
            <div class="layui-input-inline">
                <input type="text" name="permissionName" lay-verify="required" autocomplete="off" class="layui-input"
                       disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户姓别</label>
            <div class="layui-input-inline">
                <input type="text" name="userSex" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">民族</label>
            <div class="layui-input-inline">
                <input type="text" name="userNation" lay-verify="required" autocomplete="off" class="layui-input"
                       disabled>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">用户地址</label>
            <div class="layui-input-block">
                <input type="text" name="userAddress" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号</label>
            <div class="layui-input-inline">
                <input type="text" name="userTel" lay-verify="required" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <img src="" id="viewPic" style="width: 200px;height: 300px;position: absolute;right: 100px;top: 50px">
    </form>
</div>
<div id="editUser" style="display: none;position: relative;margin: 50px">
    <form class="layui-form layui-form-pane" lay-filter="editForm" id="editForm" action="">
        <div class="layui-form-item" style="display: none">
            <label class="layui-form-label">用户Id</label>
            <div class="layui-input-inline">
                <input type="text" name="userId" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户姓名</label>
            <div class="layui-input-inline">
                <input type="text" name="userName" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户账号</label>
            <div class="layui-input-inline">
                <input type="text" name="userUsername" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户密码</label>
            <div class="layui-input-inline">
                <input type="password" name="userPassword" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">职务</label>
            <div class="layui-input-inline">
                <select name="roleId" id="roleIdSelect" style="width: 100px">
                    <option selected disabled>请设置职务</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户性别</label>
            <div class="layui-input-inline">
                <input type="text" name="userSex" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">民族</label>
            <div class="layui-input-inline">
                <input type="text" name="userNation" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户地址</label>
            <div class="layui-input-block">
                <input type="text" name="userAddress" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号</label>
            <div class="layui-input-inline">
                <input type="text" name="userTel" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" style="display: none">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-inline">
                <input type="text" name="userStatus" lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-upload" style="display:inline-block;position: absolute;right: 100px;top:0">
            <button type="button" class="layui-btn" id="test1">更换图片</button>
            <div class="layui-upload-list">
                <img class="layui-upload-img" id="editUserPic" src="" style="width: 200px;height: 300px;">
                <p id="demoText"></p>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="submit" class="layui-btn" lay-submit="" lay-filter="sub">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="insert">新增</button>
        <button class="layui-btn layui-btn-sm" lay-event="startUsing" style="background-color: #31BDEC">启用</button>
        <button class="layui-btn layui-btn-sm" lay-event="stopUsing" style="background-color: #FFB800">停用</button>
        <button class="layui-btn layui-btn-sm" lay-event="delete" style="background-color: #FF5722">删除选中用户
        </button>
    </div>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="view">查看</a>
    <a class="layui-btn layui-btn-xs" lay-event="modifyStatus">修改状态</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/javascript">
    $(function () {
        while ($("#roleIdSelect>option").length > 0) {
            $("#roleIdSelect>option:eq(0)").remove();
        }
        $("#roleIdSelect").append('<option value="0" disabled selected>请选择职务</option>')
        $("#queryRoleSelect").append('<option value="0" disabled selected>请选择职务</option>')
        $.ajax({
            url: '/role/queryAllRole',
            type: 'get',
            dataType: 'json',
            success: function (res) {
                let data = res.data;
                for (let i in data) {
                    $("#roleIdSelect").append('<option value="' + data[i].roleId + '">' + data[i].roleName + '</option>')
                    $("#queryRoleSelect").append('<option value="' + data[i].roleId + '">' + data[i].roleName + '</option>')
                }
            }
        })
        $("#resetButton").click(function () {
            $("#userName").val("");
            $("#queryRoleSelect").val(0);
            $("#userStatus").val(0);
        })
    })
</script>
<script>
    layui.use(['table', 'dropdown', 'form', 'upload'], function () {
        var table = layui.table;
        var dropdown = layui.dropdown;
        let form = layui.form;
        let upload = layui.upload;
        // 上传图片
        let uploadInst = upload.render({
            elem: '#test1'
            , url: '/upload/pictureUpload'
            , done: function (res) {
                //如果上传失败
                if (res.code == 0) {
                    layer.msg('上传成功');
                    $("#editUserPic").attr("src", res.data);
                } else {
                    layer.msg("上传失败")
                }
            }
        })
        var $ = layui.$, active = {
            reload: function () {
                var userName = $("#userName");
                var roleId = $("#queryRoleSelect");
                var userStatus = $("#userStatusSelect");
                console.log(userName.val())
                console.log(roleId.val())
                console.log(userStatus.val())
                //执行重载
                layer.msg(0)
                table.reload('test', {
                    url: '/user/queryAllUser',
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                        name: userName.val() == "" ? null : userName.val(),
                        roleId: roleId.val() == 0 ? null : roleId.val(),
                        status: userStatus.val() == 0 ? null : userStatus.val()
                    }
                });
            }
        }
        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        // 创建渲染实例
        table.render({
            elem: '#test'
            , url: '/user/queryAllUser'
            , toolbar: '#toolbarDemo'
            , defaultToolbar: ['filter', 'exports', 'print', {
                title: '帮助'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , height: 'full-200'
            , cellMinWidth: 80
            , totalRow: true
            , page: true
            , limit: 10
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'userId', fixed: 'left', width: 80, title: 'ID', sort: true, totalRowText: '合计：'}
                , {field: 'userName', width: 80, title: '姓名'}
                , {field: 'userUsername', width: 80, title: '用户'}
                , {
                    field: 'roleName', width: 80, title: '职务', templet: function (data) {
                        return data.role.roleName;
                    }
                }
                , {
                    field: 'permissionName', width: 80, title: '权限', templet: function (data) {
                        return data.role.permission.permissionName;
                    }
                }
                , {field: 'userSex', width: 80, title: '性别', sort: true}
                , {field: 'userNation', width: 80, title: '民族', sort: true}
                , {field: 'userTel', width: 80, title: '电话', sort: true}
                , {field: 'userAddress', title: '地址', minWidth: 260, style: '-moz-box-align: start;'}
                , {
                    field: 'userStatus', width: 100, title: '状态', templet: function (data) {
                        if (data.userStatus == 1)
                            return '<span style="color: #00FF00">启用</span>';
                        else
                            return '<span style="color: #d43f3a">停用</span>';
                    }
                }
                , {fixed: 'right', title: '操作', width: 270, minWidth: 270, toolbar: '#barDemo'}
            ]]
        });

        // 更多测试
        dropdown.render({
            elem: '#moreTest' //可绑定在任意元素中，此处以上述按钮为例
            , data: [{
                id: 'add',
                title: '添加'
            }, {
                id: 'update',
                title: '编辑'
            }, {
                id: 'delete',
                title: '删除'
            }]
            //菜单被点击的事件
            , click: function (obj) {
                var checkStatus = table.checkStatus(id)
                var data = checkStatus.data; // 获取选中的数据
                switch (obj.id) {
                    case 'add':
                        layer.open({
                            title: '添加',
                            type: 1,
                            area: ['80%', '80%'],
                            content: '<div style="padding: 16px;">自定义表单元素</div>'
                        });
                        break;
                    case 'update':
                        if (data.length !== 1) return layer.msg('请选择一行');
                        layer.open({
                            title: '编辑',
                            type: 1,
                            area: ['80%', '80%'],
                            content: '<div style="padding: 16px;">自定义表单元素</div>'
                        });
                        break;
                    case 'delete':
                        if (data.length === 0) {
                            return layer.msg('请选择一行');
                        }
                        layer.msg('delete event');
                        break;
                }
            }
        });


        // 工具栏事件
        table.on('toolbar(test)', function (obj) {
            // 整个表的数据
            // var getData = table.getData(id);
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = lay(this);
            switch (obj.event) {
                case 'insert':
                    form.val('editForm', {
                        'userId': 0,
                        'userName': '',
                        'userUsername': '',
                        'userPassword': '',
                        'roleId': 0,
                        'userSex': '',
                        'userNation': '',
                        'userAddress': '',
                        'userTel': '',
                        'userStatus': 1
                    });
                    $("#test1").html("上传照片")
                    $("#editUserPic").attr("src", "");
                    $("#editForm").attr("action", '/user/insertUser')
                    editDiv = layer.open({
                        title: '新增',
                        type: 1,
                        area: ['60%', '80%'],
                        content: $("#editUser"),
                        shade: 0
                    });
                    break;
                case 'startUsing':
                    var data = checkStatus.data;
                    var userIdList = new Array()
                    for (var i in data) {
                        userIdList.push(data[i].userId)
                    }
                    $.ajax({
                        url: '/user/updateUserStatus',
                        type: 'put',
                        dataType: 'json',
                        data: JSON.stringify({userIds: userIdList, userStatus: 1}),
                        contentType: 'application/json',
                        success: function (res) {
                            if (res.code == 0) {
                                table.reload("test")
                            }
                        }
                    })
                    break;
                case 'stopUsing':
                    var data = checkStatus.data;
                    var userIdList = new Array()
                    for (var i in data) {
                        userIdList.push(data[i].userId)
                    }
                    $.ajax({
                        url: '/user/updateUserStatus',
                        type: 'put',
                        dataType: 'json',
                        data: JSON.stringify({userIds: userIdList, userStatus: 2}),
                        contentType: 'application/json',
                        success: function (res) {
                            if (res.code == 0) {
                                table.reload("test")
                            }
                        }
                    })
                    break;
                case 'delete':
                    layer.confirm('确定删除？', function (index) {
                        var data = checkStatus.data;
                        var userIdList = new Array()
                        for (var i in data) {
                            userIdList.push(data[i].userId)
                        }
                        $.ajax({
                            url: '/user/deleteUser',
                            type: 'delete',
                            dataType: 'json',
                            data: JSON.stringify({userIds: userIdList}),
                            contentType: 'application/json',
                            success: function (res) {
                                if (res.code == 0) {
                                    layer.msg("删除成功")
                                    table.reload("test")
                                } else {
                                    lay.msg(res.msg)
                                }
                            }
                        })
                        layer.close(index)
                    })
                    break;
            }
        });

        //触发单元格工具事件
        table.on('tool(test)', function (obj) { // 双击 toolDouble
            var data = obj.data;
            //console.log(obj)
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                form.val('editForm', {
                    'userId': data.userId,
                    'userName': data.userName,
                    'userUsername': data.userUsername,
                    'userPassword': data.userPassword,
                    'roleId': data.role.roleId,
                    'userSex': data.userSex,
                    'userNation': data.userNation,
                    'userAddress': data.userAddress,
                    'userTel': data.userTel,
                    'userStatus': data.userStatus
                })
                $("#test1").html("更换照片")
                $("#editUserPic").attr("src", data.userPic);
                $("#editForm").attr("action", '/user/updateUser')
                editDiv = layer.open({
                    title: '编辑',
                    type: 1,
                    area: ['60%', '80%'],
                    content: $("#editUser"),
                    shade: 0
                });
            } else if (obj.event === 'view') {
                form.val('viewForm', {
                    'userName': data.userName,
                    'userUsername': data.userUsername,
                    'roleName': data.role.roleName,
                    'permissionName': data.role.permission.permissionName,
                    'userSex': data.userSex,
                    'userNation': data.userNation,
                    'userAddress': data.userAddress,
                    'userTel': data.userTel
                })
                $("#viewPic").attr("src", data.userPic);
                layer.open({
                    title: '个人信息',
                    type: 1,
                    area: ['60%', '60%'],
                    content: $("#userItem"),
                    shade: 0
                });
            } else if (obj.event === "modifyStatus") {
                console.log(data)
                var userIds = [data.userId]
                let userStatus = 1;
                if (data.userStatus == 1) {
                    userStatus = 2;
                }
                console.log(userIds)
                $.ajax({
                    url: '/user/updateUserStatus',
                    type: 'put',
                    data: JSON.stringify({
                        userIds: userIds,
                        userStatus: userStatus
                    }),
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (data) {
                        if (data.code == 0) {
                            table.reload('test')
                            layer.close("editDiv");
                        } else {
                            layer.msg(data.msg)
                        }
                    }
                })
            }
        });
        form.on('submit(sub)', function (data) {
            let da = data.field;
            da.userPic = $("#editUserPic").attr("src")
            let url = $("#editForm").attr("action")
            $.ajax({
                url: url,
                type: 'put',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(da),
                success: function (data) {
                    if (data.code == 0) {
                        layer.msg("成功")
                        table.reload("test");
                        layer.close(editDiv)
                    } else {
                        layer.msg(data.msg)
                    }
                }
            })
            return false;
        })
    })
</script>
</body>
</html>